<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" ref="queryRef" :model="queryParams" class="demo-form-inline" label-width="80px"
      v-show="showSearch">
      <el-form-item label="项目编号" prop="projectNo">
        <el-input v-model="queryParams.projectNo" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery"
          style="width: 194px;" />
      </el-form-item>
      <el-form-item label="井号" prop="wellNo">
        <el-input v-model="queryParams.wellNo" placeholder="请输入井号" clearable @keyup.enter="handleQuery"
          style="width: 194px;" />
      </el-form-item>
      <el-form-item label="收入单位" prop="deptName">
        <el-tree-select v-model="queryParams.deptName" :data="deptOptions" style="width: 194px;" filterable clearable
          :props="{ value: 'label', label: 'label', children: 'children' }" value-key="id" placeholder="请选择收入单位"
          check-strictly @change="handleQuery" />
      </el-form-item>
      <el-form-item label="开工日期" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
          style="width: 194px;" placeholder="请选择开工日期" @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="完工日期" prop="completeMonth">
        <el-date-picker clearable v-model="queryParams.completeMonth" type="date" value-format="YYYY-MM-DD"
          style="width: 194px;" placeholder="请选择完工日期" @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="付款单位" prop="paymentdeptName">
        <el-select v-model="queryParams.paymentdeptName" placeholder="请选择付款单位" style="width: 194px;" filterable clearable
          @change="handleQuery">
          <el-option v-for="item in PaydeptList" :key="item.id" :label="item.paymentDeptName"
            :value="item.paymentDeptName"></el-option>
        </el-select>
        <!-- <el-input v-model="queryParams.paymentdeptName" placeholder="请输入付款单位" clearable @keyup.enter="handleQuery" /> -->
      </el-form-item>
      <el-form-item label="施工队伍" prop="deptThreeName">
        <el-input v-model="queryParams.deptThreeName" placeholder="请输入施工队名称" clearable @keyup.enter="handleQuery"
          style="width: 194px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据展示表格 -->
    <el-row :gutter="10" class="mb8">
      <!-- 操作行 -->
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:management:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:management:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:management:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" size="mini" @click="handleExport"
          v-hasPermi="['system:management:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="tableData" style="width: 100%" max-height="500"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="projectNo" label="项目编号" align="center" width="200" />
      <el-table-column prop="wellNo" label="井号" align="center" width="150" />
      <el-table-column prop="shortNo" label="井号简称" align="center" width="150" />
      <el-table-column prop="projectType" label="项目类型" align="center" width="150">
        <template #default="scope">
          <dict-tag :options="orgtype_dept" :value="scope.row.projectType" />
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="收入单位" align="center" width="200" />
      <el-table-column prop="startTime" label="开工日期" align="center" sortable width="150" />
      <el-table-column prop="completeMonth" label="完工日期" align="center" sortable width="150" />
      <el-table-column prop="constructionName" label="生产施工分类" align="center" width="150">
        <!-- <template #default="scope">
          <dict-tag :options="construction_flag" :value="scope.row.constructionId" />
        </template> -->
      </el-table-column>
      <el-table-column prop="operateName" label="经营施工分类" align="center" width="150">
        <!-- <template #default="scope">
          <dict-tag :options="construction_flag" :value="scope.row.constructionId" />
        </template> -->
      </el-table-column>
      <el-table-column prop="constructionAddress" label="施工地点" align="center" width="150">
        <template #default="scope">
          <dict-tag :options="construction_address" :value="scope.row.constructionAddress" />
        </template>
      </el-table-column>
      <el-table-column prop="deptThreeName" label="施工队伍" align="center" width="200" />
      <el-table-column prop="constructionContent" label="施工内容" align="center" width="150" />
      <el-table-column prop="paymentdeptName" label="付款单位" align="center" width="200" />
      <el-table-column prop="createBy" label="创建人" align="center" width="150" />
      <el-table-column prop="createTime" label="立项时间" align="center" sortable width="150" />
      <el-table-column label="操作" width="180" align="center" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:management:edit']">修改</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdateTiem(scope.row)"
            v-hasPermi="['system:management:edit']">时间填写</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:management:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增修改弹框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="postRef" :model="formData" :rules="rules" label-width="110px">
        <el-form-item label="井号" prop="wellNo">
          <el-input v-model="formData.wellNo" placeholder="请输入井号" class="el-width" :disabled="timeUpdete">
          </el-input>
        </el-form-item>
        <el-form-item label="井号简称" prop="shortNo">
          <el-input v-model="formData.shortNo" placeholder="井号简称" class="el-width" :disabled="timeUpdete">
          </el-input>
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="formData.projectType" placeholder="请选择项目类型" class="el-width" :disabled="timeUpdete">
            <el-option v-for="dict in orgtype_dept" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收入单位" prop="deptName">
          <el-tree-select v-model="formData.deptName" :data="deptOptions" class="el-width" :disabled="timeUpdete"
            filterable clearable :props="{ value: 'label', label: 'label', children: 'children' }" value-key="id"
            placeholder="请选择收入单位" check-strictly @change="getdeptId" />
        </el-form-item>
        <el-form-item label="施工单位" prop="deptThreeName">
          <el-tree-select v-model="formData.deptThreeName" :data="constructionList" class="el-width" filterable clearable
            :disabled="timeUpdete" :props="{ value: 'label', label: 'label', children: 'children' }" value-key="id"
            placeholder="请选择施工单位" check-strictly @change="getConstructionId" />
        </el-form-item>
        <el-form-item label="开工日期" prop="startTime">
          <el-date-picker v-model="formData.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开工日期"
            class="el-width" />
        </el-form-item>
        <el-form-item label="完工日期" prop="startTime">
          <el-date-picker v-model="formData.completeMonth" type="date" value-format="YYYY-MM-DD" placeholder="请选择完工日期"
            class="el-width" />
        </el-form-item>
        <el-form-item label="生产施工分类" prop="constructionName">
          <el-select v-model="formData.constructionName" placeholder="请选择生产施工分类" class="el-width" :disabled="timeUpdete"
            filterable clearable @change="getconstructionTypeId">
            <el-option v-for="item in ConstructionTypeList" :key="item.id" :label="item.constructionName"
              :value="item.constructionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经营施工分类" prop="operateName">
          <el-select v-model="formData.operateName" placeholder="请选择经营施工分类" class="el-width" :disabled="timeUpdete"
            filterable clearable @change="getOperateTypeId">
            <el-option v-for="item in operateList" :key="item.id" :label="item.constructionName"
              :value="item.constructionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="施工地点" prop="constructionAddress">
          <el-select v-model="formData.constructionAddress" placeholder="请选择施工地点" class="el-width" :disabled="timeUpdete">
            <el-option v-for="dict in construction_address" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="施工内容" prop="constructionContent">
          <el-input v-model="formData.constructionContent" placeholder="请输入施工内容" class="el-width" :disabled="timeUpdete"
            autosize type="textarea">
          </el-input>
        </el-form-item>
        <el-form-item label="付款单位" prop="paymentdeptName">
          <el-select v-model="formData.paymentdeptName" placeholder="请选择付款单位" class="el-width" :disabled="timeUpdete"
            filterable clearable @change="getpaymentdeptId">
            <el-option v-for="item in PaydeptList" :key="item.id" :label="item.paymentDeptName"
              :value="item.paymentDeptName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { listManagement, getManagement, addManagement, updateManagement, delManagement, listTwoDept, listPaydept, listConstructionType } from '@/api/system/projectManagement';
import { pinyin } from 'pinyin-pro'

// 字典引入
const { proxy } = getCurrentInstance();
const { construction_address, orgtype_dept } = proxy.useDict('construction_address', 'orgtype_dept');
// const { construction_address } = proxy.useDict('construction_address');

//部门下拉树
const deptOptions = ref()
const constructionList = ref()
const operateList = ref()
const PaydeptList = ref()
const queryPaydeptList = ref()
const ConstructionTypeList = ref()
//表单显示隐藏
const showSearch = ref(true);
// 表格数据
const tableData = ref([])
const loading = ref(true);
// 数据总数
const total = ref(0)
const open = ref(false)
const title = ref()
const update = ref(true)
const timeUpdete = ref(false)
//打开弹框

// 删除的ids
const ids = ref([]);
// 单选
const single = ref(true)
// 多选
const multiple = ref(true);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
// 表单字段
const formData = ref({
  wellNo: '',
  shortNo: '',
  projectType: '',
  deptName: '',
  deptId: '',
  deptThreeId: '',
  deptThreeName: '',
  startTime: '',
  completeMonth: '',
  constructionId: '',
  constructionAddress: '',
  constructionContent: '',
  paymentdeptId: '',
})
// 表单规则
const rules = ref({
  wellNo: [{ required: true, message: "井号不能为空", trigger: "blur" }],
  projectType: [{ required: true, message: "项目类型不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "收入单位不能为空", trigger: "blur" }],
  deptThreeName: [{ required: true, message: "施工单位不能为空", trigger: "blur" }],
  constructionName: [{ required: true, message: "生产施工分类不能为空", trigger: "blur" }],
  constructionAddress: [{ required: true, message: "施工地点不能为空", trigger: "blur" }],
  constructionContent: [{ required: true, message: "施工内容不能为空", trigger: "blur" }],
  paymentdeptName: [{ required: true, message: "付款单位不能为空", trigger: "blur" }]
})
// 表单重置
const reset = () => {
  formData.value = {
    id: null,
    projectNo: null,
    wellNo: null,
    shortNo: null,
    projectType: null,
    deptName: null,
    deptId: null,
    startTime: null,
    completeMonth: null,
    constructionId: null,
    sysOrgCode: null,
    constructionName: null,
    constructionAddress: null,
    constructionContent: null,
    paymentdeptId: null,
    paymentdeptName: null,
    updateBy: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    deptThreeId: null,
    deptThreeName: null
  };
  proxy.resetForm("postRef");
  timeUpdete.value = false
}
//获取列表数据
const getList = () => {
  loading.value = true;
  listManagement(queryParams.value).then(res => {
    tableData.value = res.rows
    total.value = res.total;
    loading.value = false;
  }).catch(error => {
    console.log(error);
  })
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listTwoDept({ parentId: 100 }).then(res => {
    //二级部门
    deptOptions.value = res.data.map(item => ({
      label: item.deptName,
      id: item.deptId,
      children: item.children
    }))
  })
};
/**收入单位ID */
function getdeptId(Name) {
  const list = deptOptions.value.find(item => item.label == Name)
  formData.value.deptId = list.id
}
/**查询该分公司的施工队伍 */
function getConstructionList(deptId) {
  listTwoDept({ parentId: deptId }).then(res => {
    constructionList.value = res.data.map(item => ({
      label: item.deptName,
      id: item.deptId,
      children: item.children
    }))
  })
}
/**施工队伍ID */
function getConstructionId(Name) {
  const list = constructionList.value.find(item => item.label == Name)
  formData.value.deptThreeId = list.id
}
/**查询该项目类型的付款单位 */
function getPaydeptList() {
  listPaydept().then(res => {
    PaydeptList.value = res.data
  })
}
/**付款单位ID */
function getpaymentdeptId(Name) {
  const list = PaydeptList.value.find(item => item.paymentDeptName == Name)
  formData.value.paymentdeptId = list.id
}

/**查询生产施工分类 */
function getConstructionType(typeId) {
  listConstructionType({ constructionFlag: 1 }).then(res => {
    ConstructionTypeList.value = res.rows
  })
}
function getOperateType(typeId) {
  listConstructionType({ constructionFlag: 2 }).then(res => {
    operateList.value = res.rows
  })
}
/**施工分类ID */
function getconstructionTypeId(Name) {
  const list = ConstructionTypeList.value.find(item => item.constructionName == Name)
  formData.value.constructionId = list.id
}
/**施工分类ID */
function getOperateTypeId(Name) {
  const list = ConstructionTypeList.value.find(item => item.constructionName == Name)
  formData.value.operateId = list.id
}
//获取该分公司的小队
watch(
  () => formData.value.deptId,
  (newValue) => {
    getConstructionList(newValue)
  }
), { immediate: true }
//获取对应项目类型的付款单位
// watch(
//   () => formData.value.projectType,
//   (newValue) => {
//     getPaydeptList(newValue);
//   }
// ), { immediate: true }

//转换井号简称
watch(
  () => formData.value.wellNo,
  (newValue) => {
    if (newValue) {
      formData.value.shortNo = pinyin(newValue, { pattern: 'first', toneType: 'string', separator: '' }).toUpperCase();
    } else {
      formData.value.shortNo = ''
    }
  }
), { immediate: true }

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增"
  update.value = false
}
/** 编辑按钮操作 */
function handleUpdate(row) {
  reset()
  getManagement(row.id).then(response => {
    formData.value = response.data;
    open.value = true;
    title.value = "修改";
    update.value = true
  });
}
/**修改时间 */
function handleUpdateTiem(row) {
  reset()
  getManagement(row.id).then(response => {
    formData.value = response.data;
    open.value = true;
    title.value = "修改时间";
    update.value = true
    timeUpdete.value = true
  });
}
// 提交
const submitForm = () => {
  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (update.value) {
        updateManagement(formData.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addManagement(formData.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
// 取消
const cancel = () => {
  open.value = false
  reset();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const delId = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除?').then(function () {
    return delManagement(delId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });

}
/**导出按钮操作 */
function handleExport() {
  proxy.download("/system/management/export", {
    ...queryParams.value
  }, `项目列表.xlsx`);
}

//查询列表
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
getPaydeptList()
getConstructionType()
getOperateType()
getDeptTree();
getList();
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
}

.search-form {
  padding-left: 20px;
}

.el-width {
  width: 340px;
}
</style>